package com.ruoyi.business.service.koc.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.domain.dto.admin.user.TbUserAddressPageQueryDTO;
import com.ruoyi.business.domain.dto.api.user.AddMyAddressDTO;
import com.ruoyi.business.domain.dto.api.user.EditMyAddressDTO;
import com.ruoyi.business.domain.koc.TbUserAddress;
import com.ruoyi.business.mapper.koc.TbUserAddressMapper;
import com.ruoyi.business.service.koc.ITbUserAddressService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;

/**
 * 用户收货地址Service业务层处理
 *
 * @author ruoyi
 */
@RequiredArgsConstructor
@Service
public class TbUserAddressServiceImpl extends ServiceImpl<TbUserAddressMapper, TbUserAddress> implements ITbUserAddressService {

    /**
     * 查询用户收货地址列表
     *
     * @return 用户收货地址
     */
    @Override
    public TableDataInfo<TbUserAddress> queryPageList(TbUserAddressPageQueryDTO dto, PageQuery pageQuery) {
        LambdaQueryWrapper<TbUserAddress> tbUserAddressLambdaQueryWrapper = Wrappers.lambdaQuery(TbUserAddress.class)
            .like(StringUtils.isNotEmpty(dto.getReceiverName()), TbUserAddress::getReceiverName, dto.getReceiverName())
            .like(StringUtils.isNotEmpty(dto.getReceiverPhone()), TbUserAddress::getReceiverPhone, dto.getReceiverPhone())
            .orderByDesc(TbUserAddress::getCreateTime);
        Page<TbUserAddress> page = this.page(pageQuery.build(), tbUserAddressLambdaQueryWrapper);
        return TableDataInfo.build(page);
    }


    /**
     * 批量删除用户收货地址
     *
     * @param ids 需要删除的用户收货地址主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(Collection<String> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<TbUserAddress> queryMyAddressPageList(Long userId, PageQuery pageQuery) {
        LambdaQueryWrapper<TbUserAddress> tbUserAddressLambdaQueryWrapper = Wrappers.lambdaQuery(TbUserAddress.class).eq(TbUserAddress::getUserId, userId).orderByDesc(TbUserAddress::getIsDefault).orderByDesc(TbUserAddress::getCreateTime);
        Page<TbUserAddress> page = this.page(pageQuery.build(), tbUserAddressLambdaQueryWrapper);
        return TableDataInfo.build(page);
    }

    @Override
    public Boolean insertMyAddress(Long userId, AddMyAddressDTO dto) {
        // 默认地址只有一个
        if (Constants.TRUE_1.equals(dto.getIsDefault())) {
            boolean exists = this.baseMapper.exists(Wrappers.lambdaQuery(TbUserAddress.class)
                .eq(TbUserAddress::getIsDefault, Constants.TRUE_1)
                .eq(TbUserAddress::getUserId, userId)
                .eq(TbUserAddress::getStatus, Constants.TRUE_1));
            if (exists) {
                throw new ServiceException("默认地址已存在");
            }
        }
        TbUserAddress tbUserAddress = BeanUtil.toBean(dto, TbUserAddress.class);
        tbUserAddress.setId(IdWorker.getId());
        tbUserAddress.setUserId(userId);
        tbUserAddress.setCreateTime(new Date());
        return this.save(tbUserAddress);
    }

    @Override
    public Boolean editMyAddress(Long userId, EditMyAddressDTO dto) {
        TbUserAddress tbUserAddress = this.getById(dto.getId());
        tbUserAddress.setReceiverName(StringUtils.isNotEmpty(dto.getReceiverName()) ? dto.getReceiverName() : StringUtils.EMPTY);
        tbUserAddress.setReceiverPhone(StringUtils.isNotEmpty(dto.getReceiverPhone()) ? dto.getReceiverPhone() : StringUtils.EMPTY);
        tbUserAddress.setCountryCode(StringUtils.isNotEmpty(dto.getCountryCode()) ? dto.getCountryCode() : StringUtils.EMPTY);
        tbUserAddress.setProvinceName(StringUtils.isNotEmpty(dto.getProvinceName()) ? dto.getProvinceName() : StringUtils.EMPTY);
        tbUserAddress.setCityName(StringUtils.isNotEmpty(dto.getCityName()) ? dto.getCityName() : StringUtils.EMPTY);
        tbUserAddress.setDistrictName(StringUtils.isNotEmpty(dto.getDistrictName()) ? dto.getDistrictName() : StringUtils.EMPTY);
        tbUserAddress.setStreetName(StringUtils.isNotEmpty(dto.getStreetName()) ? dto.getStreetName() : StringUtils.EMPTY);
        tbUserAddress.setDetailAddress(StringUtils.isNotEmpty(dto.getDetailAddress()) ? dto.getDetailAddress() : StringUtils.EMPTY);
        tbUserAddress.setPostalCode(StringUtils.isNotEmpty(dto.getPostalCode()) ? dto.getPostalCode() : StringUtils.EMPTY);
        tbUserAddress.setAddressTag(StringUtils.isNotEmpty(dto.getAddressTag()) ? dto.getAddressTag() : StringUtils.EMPTY);
        tbUserAddress.setLongitude(ObjectUtils.isNotEmpty(dto.getLongitude()) ? dto.getLongitude() : null);
        tbUserAddress.setLatitude(ObjectUtils.isNotEmpty(dto.getLatitude()) ? dto.getLatitude() : null);
        tbUserAddress.setStatus(ObjectUtils.isNotEmpty(dto.getStatus()) ? dto.getStatus() : Constants.TRUE_1);
        tbUserAddress.setUpdateTime(new Date());
        return this.updateById(tbUserAddress);
    }

    @Override
    public Boolean setMyDefaultAddress(Long userId, Long addressId) {
        TbUserAddress byId = this.getById(addressId);
        this.update(Wrappers.lambdaUpdate(TbUserAddress.class)
            .set(TbUserAddress::getIsDefault, Constants.FALSE_0)
            .eq(TbUserAddress::getUserId, userId)
            .eq(TbUserAddress::getIsDefault, Constants.TRUE_1));
        byId.setIsDefault(Constants.TRUE_1);
        return this.updateById(byId);
    }
}
